﻿var amoy = new GLatLng(24.487383946999405, 118.1313369424438);
var center;
// var marker;
var map;

function initialize(lat, lng, isEditable, mapCanvasId, title) {
    var zoom = 15;
    if (lat && parseFloat(lat) != 0 && lng && parseFloat(lng) != 0) {
        center = new GLatLng(lat, lng);
    }
    else {
        center = amoy;
        zoom = 12;
    }

    //    var mapOptions = {
    //        zoom: zoom,
    //        mapTypeId: google.maps.MapTypeId.ROADMAP,
    //        center: center,
    //        zoomControl: true,
    //        zoomControlOptions: {
    //            style: google.maps.ZoomControlStyle.LARGE,
    //            position: google.maps.ControlPosition.LEFT_CENTER
    //        }
    //    };

    if (!mapCanvasId) {
        mapCanvasId = "map_canvas";
    }
    map = new GMap2(document.getElementById(mapCanvasId)); //, mapOptions);
    if (isEditable) {
        GEvent.addListener(map, 'click', setMarker);
    }
    var letteredIcon = new GIcon(baseIcon);

    letteredIcon.image = "/Images/marker.png";

    // Set up our GMarkerOptions object
    var markerOptions = { icon: letteredIcon, draggable: isEditable };
    var marker;
    if (lat && lng) {
        //清除地图原有标记
        // map.clearOverlays();
        marker = new GMarker(center, markerOptions);
        map.addOverlay(marker);
        if (isEditable) {
            GEvent.addListener(marker, "dragend", dragEnd);
        }
        if (title) {
            GEvent.addListener(marker, "mouseover", function () {
                var html = "<h4 class='fcbl'>" + title + "</h4>";
                marker.openInfoWindowHtml(html);
            });
        }
    }
    map.addControl(new GLargeMapControl()); //比较大的地图工具（左上角）
    map.addControl(new GMapTypeControl()); //地图类型切换控件(如：地图和卫星图)
    map.setMapType(G_HYBRID_MAP);
    map.setCenter(center, zoom);
    map.enableScrollWheelZoom();
    if (marker)
        return marker;
}

function setMarker(overlay, latlng) {
    //清除地图原有标记
    map.clearOverlays();
    var marker = new GMarker(latlng, { draggable: true });
    map.addOverlay(marker);
    GEvent.addListener(marker, "dragend", dragEnd);

    $("#Latitude").val(latlng.lat());
    $("#Longitude").val(latlng.lng());
}

function dragEnd(latlng) {
    $("#Latitude").val(latlng.lat());
    $("#Longitude").val(latlng.lng());
}

/* 楼盘附属信息标记 */

var lastLat;
var lastLng;
var currentProjectInfoState;

function initializeProjectInfoEdit() {
    $(".projectInfoContainter").each(function () {
        bindProjectInfoContainter($(this));
    });

    $(".addProjectInfo").click(function () {
        var projectState = $(this).attr("projectState");
        if (projectState != "-1") {
            var newHtml = $("#template" + projectState).children().clone();
            newHtml.insertBefore($(this).parent());
            bindProjectInfoContainter(newHtml);
        }
        else {
            // 标注楼盘位置
            setCurrentMarker($("#Latitude"), $("#Longitude"), projectState);
            $.scrollTo($("#DivToScrollTo"), 300);
        }
    });

    $("input.ProjectInfoRemark").change(function () {
        $(this).val($(this).val().replace(/,/g, "，"));
    });
}

function bindProjectInfoContainter(projectInfoContainter) {
    projectInfoContainter.find(".removeProjectState").click(function () {
        $(this).parent().remove();
        endSetCurrentMarker();
    });
    projectInfoContainter.find("input.ProjectInfoRemark").change(function () {
        $(this).val($(this).val().replace(/,/g, "，"));
    });

    projectInfoContainter.find("input.setMarker").click(function () {
        setCurrentMarker($(this).next(), $(this).next().next(), $(this).attr("ProjectInfoState"));
        $.scrollTo($("#DivToScrollTo"), 300)
    });

    projectInfoContainter.find("input[type=text]").change(function () {
        if ($(this).attr("name").indexOf("ProjectInfoState") > -1) {
            $(this).parent().attr("ProjectInfoTitle", $(this).val());
        }
        else if ($(this).attr("name").indexOf("ProjectInfoRemark") > -1) {
            $(this).parent().attr("ProjectInfoRemark", $(this).val());
        }
    });
}

function setCurrentMarker(lat, lng, projectInfoState) {
    lastLat = lat;
    lastLng = lng;
    currentProjectInfoState = projectInfoState;
    GEvent.addListener(map, 'click', setProjectInfoMarker);
    setTimeout(function () {
        var marker = null;
        map.clearOverlays();
        var letteredIcon = new GIcon(baseIcon);
        var type = currentProjectInfoState;
        if (type >= 0) {
            letteredIcon.image = "/Images/marker" + type  + "new.png";
        }
        else {
            letteredIcon.image = "/Images/markernew.png";
        }
        // Set up our GMarkerOptions object
        markerOptions = { icon: letteredIcon, draggable: true };

        if (lat.val() && lng.val()) {
            marker = new GMarker(new GLatLng(lat.val(), lng.val()), markerOptions);
        }
        else {
            marker = new GMarker(map.getCenter(), markerOptions);
        }
        if (marker) {
            // 动画

            map.addOverlay(marker);
            GEvent.addListener(marker, "dragend", dragEndProjectInfo);
            showEditTip(marker);
        }
    }, 400);
}

// lat, lng 是 input hidden jquery object
function endSetCurrentMarker() {
    lastLat = null;
    lastLng = null;
    currentProjectInfoState = '';
    GEvent.clearListeners(map, 'click');
    refreshProjectInfoMarker();
}


function setProjectInfoMarker(overlay, latlng) {
    if (!latlng)
        return;

    //清除地图原有标记
    map.clearOverlays();
    var letteredIcon = new GIcon(baseIcon);
    var type = currentProjectInfoState;
    if (type >= 0) {
        letteredIcon.image = "/Images/marker" + type + "new.png";
    }
    else {
        letteredIcon.image = "/Images/markernew.png";
    }
    // Set up our GMarkerOptions object
    markerOptions = { icon: letteredIcon, draggable: true };

    var marker = new GMarker(latlng, markerOptions);
    map.addOverlay(marker);
    GEvent.addListener(marker, "dragend", dragEndProjectInfo);
    //console.debug("setProjectInfoMarker, lat=" + latlng.lat() + ",lng="+latlng.lng());
    lastLat.val(latlng.lat());
    lastLng.val(latlng.lng());
    showGInfoWindow(marker);
}

function dragEndProjectInfo(latlng) {
    showGInfoWindow(this);
    lastLat.val(latlng.lat());
    lastLng.val(latlng.lng());
}

function initializeProjectInfoMap(isEditable) {

    var lat = $("#Latitude").val();
    var lng = $("#Longitude").val();

    var zoom = 17;
    if (lat && parseFloat(lat) != 0 && lng && parseFloat(lng) != 0) {
        center = new GLatLng(lat, lng);
    }
    else {
        center = amoy;
        zoom = 12;
    }

    var mapCanvasId = "map_canvas";
    map = new GMap2(document.getElementById(mapCanvasId)); //, mapOptions);
    //    if (isEditable) {
    //        GEvent.addListener(map, 'click', setProjectInfoMarker);
    //    }
    var marker;
    if (lat && lng) {
        //清除地图原有标记
        addMarker(lat, lng, null, $("#ProjectTitle").text());
    }
    map.addControl(new GLargeMapControl()); //比较大的地图工具（左上角）
    map.addControl(new GMapTypeControl()); //地图类型切换控件(如：地图和卫星图)
    map.setMapType(G_HYBRID_MAP);
    map.setCenter(center, zoom);
    map.enableScrollWheelZoom();
}

function refreshProjectInfoMarker() {
    // 恢复标记所有地图
    center = null;
    map.clearOverlays();
    var lat = $("#Latitude").val();
    var lng = $("#Longitude").val();
    var zoom = 17;

    if (lat && parseFloat(lat) != 0 && lng && parseFloat(lng) != 0) {
        center = new GLatLng(lat, lng);
        addMarker(lat, lng, null, $("#ProjectTitle").text());
    }

    var length = $("input.Latitude").length;
    for (var j = 0; j < length; j++) {
        var lat = $("input.Latitude")[j].value;
        var lng = $("input.Longitude")[j].value;
        var container = $($("input.Latitude")[j]).parent();
        var type = parseInt(container.attr("ProjectInfoState"));
        var title = container.attr("ProjectInfoTitle");
        var description = container.attr("ProjectInfoRemark");
        var isNew = container.attr("IsNew")
        var latlng = addMarker(lat, lng, type, title, description, isNew);
        if (center == null && latlng) {
            center = latlng;
        }
    }

    if (!center) {
        center = amoy;
        zoom = 12;
    }
    map.setCenter(center, zoom);
}
var typeStrings = ["公交站", "地铁站", "超市", "菜市场", "小学", "中学"];
var appendixStrings = ["站", "站", "超市", "菜市场", "小学", "中学"];

function addMarker(lat, lng, type, title, description, isNew) {

    if (!type && type != 0)
        type = -1;
    if (isNew) {
        isNew = "new";
    } else {
    isNew = "";
    }
    if (lat && lng) {
        var latlng = new GLatLng(lat, lng);
        var letteredIcon = new GIcon(baseIcon);
        if (type >= 0) {
            letteredIcon.image = "/Images/marker" + type + isNew + ".png";
        }
        else {
            letteredIcon.image = "/Images/marker" + isNew + ".png";
        }
        // Set up our GMarkerOptions object
        markerOptions = { icon: letteredIcon };
        var marker = new GMarker(latlng, markerOptions);
        if (title) {
            var typeString = "";
            var appendix = "";
            if (type >= 0) {
                typeString = typeStrings[type] + "：";
                appendix = appendixStrings[type];
            }
            GEvent.addListener(marker, "mouseover", function () {
                var html = "<h4><span class='fcbl'>" + title + "</span>" + appendix + "</h4>";
                if (description) {
                    if (type != -1) {
                        html += "<p class='fss'>" + description + "路</p>";
                    }
                    else {
                        html += "<p class='fss'>" + description + "</p>";
                    }
                }
                marker.openInfoWindowHtml(html);
            });
        }
        map.addOverlay(marker);
        return marker;
    }
}

function showGInfoWindow(marker) {
    if (marker) {
        setTimeout(function () {
            var latlng = marker.getLatLng();
            marker.openInfoWindowHtml('<h4>标注成功！</h4><p class="fss">（' + latlng.lat() + ',' + latlng.lng() + '）</p><p><a class="fss fcbl" href="javascript:endSetCurrentMarker()">确定</a> <a class="fss fcbl" href="javascript:map.closeInfoWindow()">重来</a></p>');
        }, 300);
    }
}

function showEditTip(marker) {
    if (marker) {
        var latlng = marker.getLatLng();
        marker.openInfoWindowHtml('<h4>请拖动气泡或点击地图来标注位置</h4><p><br /><a class="fss fcbl" href="javascript:map.closeInfoWindow()">关闭</a></p>');
    }
}


var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
/* end of 楼盘附属信息标记 */